package com.ccx.coachsite.util;


import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.downloadmgr.DownloadItem;
import com.ccx.coachsite.downloadmgr.DownloadItemDao;

public class U {
	public static boolean installApplication(Context ctx,final DownloadItem item) {
		//统计内容 一定时间内完成安装
		final DownloadItemDao dItemDao = new DownloadItemDao(ctx, DownloadItemDao.INSTALL);
		dItemDao.addItem(item);
		Timer timer=new Timer();
		TimerTask task=new TimerTask() {
			@Override
			public void run() {
				dItemDao.delete(item.getSid());
			}
		};
		timer.schedule(task, 60000);//1分钟内完成安装
		return installApplication(ctx,new File(item.getFilePath()));
	}
	
	
	public static void uninstallApp(Context ctx, DownloadItem item) {
		uninstallApp(ctx,item.getPkgName());
	}
	
	private static boolean installApplication(Context ctx, File mainFile) {
		//先判断签名是否一至
		SignedReader reader = new SignedReader();
		//获取安装包中的应用 的包名
		String packageName = reader.getPackageName(ctx, mainFile);
		boolean re = true;
		PackageManager pm = ctx.getPackageManager();
		ApplicationInfo appInfo=null;
		try {
			appInfo=pm.getApplicationInfo(packageName, 0);
		} catch (Exception e) {
		}
		if(appInfo==null) //机子上还未安装该软件，可以安装
			re=true;
		else
			//比较签名是否一致
			re = reader.compareSigned(ctx, packageName, mainFile.getAbsolutePath());
		
		if(!re){
			//签名不一致,需先卸载再安装
			Toast.makeText(ctx, R.string.common_signal_conflict, Toast.LENGTH_LONG).show();
			return false;
		}
		
		String setting = Settings.System.getString(ctx.getContentResolver(), Settings.System.INSTALL_NON_MARKET_APPS);
		if (!setting.equals("1")) {
			Settings.System.putString(ctx.getContentResolver(), Settings.System.INSTALL_NON_MARKET_APPS, "1");
		}
		try {
			Uri data = Uri.fromFile(mainFile);
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(data, "application/vnd.android.package-archive");
			ctx.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (!setting.equals("1")) {
				Settings.System.putString(ctx.getContentResolver(), Settings.System.INSTALL_NON_MARKET_APPS, setting);
			}
		}
		return true;
	}

	/**
	 * 查看应用程序详细信息
	 * @param ctx
	 * @param packageName
	 */
	public static void showAppDetails(Context ctx, String packageName){
		Intent intent = new Intent();
		if(Build.VERSION.SDK_INT >= 9){//SDK 2.3以上
			intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
	        Uri uri = Uri.fromParts("package", packageName, null);  
	        intent.setData(uri); 
		} else {
			intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
			intent.putExtra("com.android.settings.ApplicationPkgName", packageName);
			intent.putExtra("pkg", packageName); //for android 2.2
		}
		ctx.startActivity(intent);
	}
	
	/**
	 * 是否是系统应用
	 * @param ctx
	 * @param packageName
	 * @return
	 */
	public static boolean isSystemPkg(Context ctx, String packageName){
		PackageManager pm = ctx.getPackageManager();
		try {
			PackageInfo pInfo=pm.getPackageInfo(packageName, 0);
			ApplicationInfo aInfo=pInfo.applicationInfo;
		   if ((aInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0){
			   return true;
		   }
		} catch (NameNotFoundException e) {
			return false;
		}
		return false;
	}
	/**
	 * 获取已安装应用的大小
	 * Author:zhuchenghua
	 * @param pkgName
	 * @return
	 */
	public static long getApplicationSize(Context ctx,String pkgName)
	{
		PackageManager pm=ctx.getPackageManager();
		try {
			ApplicationInfo appInfo=pm.getApplicationInfo(pkgName, 0);
			String pkgPath=appInfo.publicSourceDir;
			File file=new File(pkgPath);
			if(file.exists())
				return file.length();
		} catch (Exception e) {
		}
		return 0;
	}
	
	/**
	 * 获取已安装应用的大小
	 * Author:zhuchenghua
	 * @param appInfo
	 * @return
	 */
	public static long getApplicationSize(ApplicationInfo appInfo)
	{
		try {
			String pkgPath=appInfo.publicSourceDir;
			File file=new File(pkgPath);
			if(file.exists())
				return file.length();
		} catch (Exception e) {
		}
		return 0;
	}
	
	/**
	 * 卸载应用程序
	 * @param ctx
	 * @param packageName
	 */
	private static void uninstallApp(Context ctx, String packageName){
		Uri uri = Uri.fromParts("package", packageName, null);
		Intent it = new Intent(Intent.ACTION_DELETE, uri);
		ctx.startActivity(it);
	}
	
	/**
	 * 获取应用安装时间
	 * @param packageName
	 * @param ctx
	 * @return
	 */
	public static long getAppInstallTime(String packageName,Context ctx)
	{
		PackageManager pm=ctx.getPackageManager();
		try {
			ApplicationInfo appInfo=pm.getApplicationInfo(packageName, 0);
			String sourceDir = appInfo.sourceDir;
			return new File(sourceDir).lastModified();
		} catch (Exception e) {
		}
		
		return 0;
	}
	
	
	public static void hideKeyboard(Context ctx, View view){
		if( null == view ) return;
		InputMethodManager imm = (InputMethodManager)ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow( view.getWindowToken(), 0 );
	}
}
